<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
        <link href="./watchlog.css" rel="stylesheet" type="text/css" />
    </head>
    <script>
        // var url = "";
        var crumbcontent, dircontent, userid, output;

        function init() {
            dircontent = document.getElementById("dircontent");
            crumbcontent =  document.getElementById('crumbcontent');
            output = document.getElementById("output");

            getUserId();
            listfiles();
        }

        function get(url, callback) {
            let xhr = new XMLHttpRequest();
            // methods：GET/POST请求方式等，url：请求地址，true异步（可为false同步）
            xhr.open("GET", url, true);
            xhr.send();// 发送
            xhr.onreadystatechange = function () { 
                if (xhr.readyState == 4 && xhr.status == 200) {   // 成功，接收到数据
                    var result = JSON.parse(xhr.response);
                    console.log(result);
                    callback(result.data);
                } else if (xhr.status == 404) {                  // 失败，页面未找到
                }else {
                    callback([]);
                }
            }
        }

        function getUserId() {
            get("./userid", function (u) {
                userid = u;
                var iscript =  document.getElementById("iscript");
                iscript.onclick = function(){
                    showLogs("iscript/" + userid + ".log", iscript);
                };
            });
        }

        function crumb(path) {
            crumbcontent.innerHTML = "";
            var parts = (path ? "HOME/" + path : "HOME").split("/");
            var pp = "";
            parts.forEach((part, i) => {
                var a = document.createElement("a");
                a.innerText = part;
                pp += "/" + part;
                var tmp = pp.replaceAll("/HOME/", "").replaceAll("/HOME", "");
                a.onclick = function(){
                    listfiles(tmp);
                }
                crumbcontent.appendChild(a);

                if (i < parts.length - 1) {
                    var span = document.createElement("span");
                    span.innerText = ">";
                    crumbcontent.appendChild(span);
                }
            });
        }

        function listfiles(path) {
            var url = path ? "./listfiles?path=" + path : "./listfiles"
            get(url, function (list) {
                console.log("listfiles", list);

                crumb(path);
                dircontent.innerHTML = "";
                if(list.dirs) 
                    list.dirs.forEach((d,index) => {
                        var span = document.createElement("span");
                        span.setAttribute('class','tabsItem') //tabsItem默认样式
                        span.innerHTML = d;
                        var p = path ? path + '/' + d : d;
                        span.onclick = function () { listfiles(p) };
                        dircontent.appendChild(span);
                    });
                if(list.files) 
                    list.files.forEach((f,index) => {
                        var span = document.createElement("span");
                        span.setAttribute('class','tabsItem') //tabsItem默认样式
                        span.innerHTML = f;
                        var p = path ? path + '/' + f : f;
                        span.onclick = function () { showLogs(p, span) };
                        dircontent.appendChild(span);
                    });
            });
        }

        function showLogs(serviceName , elm) {
            var tabsItemArr = document.getElementsByClassName('tabsItem')
            for(let i = 0; i < tabsItemArr.length; i ++) {
                tabsItemArr[i].classList.remove('tabsItemActive')
            }
            elm.classList.add('tabsItemActive')//选中
            var idconsole = document.getElementById('console')
            var key = "$" + serviceName.replaceAll("/", "$");
            createConsoleDiv(key);
        }

        function createConsoleDiv(key,inx) {
            var ipItemArr = document.getElementsByClassName('ipItem')
            for(let i = 0; i < ipItemArr.length; i ++) {
                ipItemArr[i].classList.remove('ipItemActive')
            }
            if(ipItemArr && ipItemArr.length > 0) {
                ipItemArr[inx].classList.add('ipItemActive')//选中
            }
            var div = document.getElementById(key);
            var arr = document.getElementsByClassName("active");
            for(var i=0;i<arr.length; i++) arr[i].className = "inactive";

            if (!div) {
                div = document.createElement("div");
                div.setAttribute("id", key);
                div.style.wordWrap = "break-word";
                div.style.backgroundColor = "#555";  //所有浏览器都支持属性赋值
                // div.style.border = "1px solid blue";
                div.className = "active";

                var output = document.getElementById("output");
                output.appendChild(div);

                var websocket = connWebSocket(key);
            }
            div.className = "active";
        }

        function connWebSocket(key) {
            var consoleDiv = document.getElementById(key);
            var host = window.location.host;
            var wsUri = "ws:" + host + "/manager/websocket/" + key;
            var websocket = new WebSocket(wsUri);
            websocket.onopen = function (evt) {
                writeToScreen("CONNECTED");
                doSend("WebSocket rocks");
            };
            websocket.onclose = function (evt) {
                writeToScreen("DISCONNECTED");
            };
            websocket.onmessage = function (evt) {
                writeToScreen('<span style="color: white;">' + evt.data + '</span>');
            };
            websocket.onerror = function (evt) {
                writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
            };

            function doSend(message) {
                writeToScreen("SENT: " + message);
                websocket.send(message);
            }

            var lineCount = 0;
            function writeToScreen(message) {
                var pre = document.createElement("pre");
                pre.style.wordWrap = "break-word";
                pre.innerHTML = message;
                consoleDiv.appendChild(pre);
                lineCount ++;
                if(lineCount > 2000) { //最多显示2000行
                    consoleDiv.removeChild(consoleDiv.firstChild);
                }
            }
            return websocket;

        }

        window.addEventListener("load", init, false); 
    </script>

    <body>
        <div class="serverLog">
            <div><span class="title">服务器日志</span><span id="crumbcontent"></span><span ></span></div>
            <div><span id="dircontent"></span><span id="iscript" style="float:right">脚本输出</span></div>
            <div id="console">
                <div id="output"></div>
            </div>
        </div>
    </body>
</html>